package com.lagou.client;

import com.lagou.codec.RpcDecoder;
import com.lagou.codec.RpcEncoder;
import com.lagou.handler.UserClientHandler;
import com.lagou.request.RpcRequest;
import com.lagou.series.JSONSerializer;
import com.lagou.series.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xsl
 * @date 2021/3/13 15:23
 * @Description: RPCConsumer
 */
public class RPCConsumer {

    /**
     * 创建线程池
     */
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler clientHandler = null;

    /**
     * 通过java JDK创建代理对象,返回服务端返回的数据  providerParam :  "UserService#sayHello#"
     */
    public static Object createProxy(Class serviceClass, String methodName, Class<?>[] parameterTypes) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //初始化客户端Client
                if (clientHandler == null) {
                    initClient();
                }
                //为clientHandler设置参数
                RpcRequest request = new RpcRequest();
                request.setClassName(serviceClass.getName());
                request.setRequestId("1");
                request.setMethodName(methodName);
                request.setParameters(args);
                request.setParameterTypes(parameterTypes);
                clientHandler.setRpcRequest(request);
                //通过线程池向服务端写入数据并等待返回
                Object result = executorService.submit(clientHandler).get();
                System.out.println("服务器返回成功结果 ==========：" + result.toString());
                return result;
            }
        });
    }

    private static void initClient() throws InterruptedException {
        clientHandler = new UserClientHandler();
        Serializer serializer = new JSONSerializer();
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, serializer));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, serializer));
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(clientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1", 8999).sync();
    }
}
